﻿#include "usermanager.h"
#include "ui_usermanager.h"
#include"qpainter.h"
#include "qfiledialog.h"
// #include "qmessagebox.h"
#include "qtextstream.h"
#include "qdebug.h"

#ifdef X86
#include "QtCore5Compat/QTextDecoder"
#elif defined ARM
#include "QTextDecoder"
#endif


#include "DataBase/mysql.h"
#include "Beans/userinfobean.h"
#include "dialog/myhelper.h"
#include "dialog/updateinfo.h"
#include "constant.h"
UserManager::UserManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserManager)
{
    ui->setupUi(this);
    initTableView();
    ui->usermanager_pushButton_delete->setEnabled(false);
//    ui->usermanager_pushbutton_update->setEnabled(false);
    if(Constant::ShowFullScreen)
        this->showFullScreen();
}

UserManager::~UserManager()
{
    delete ui;
}
void UserManager::paintEvent(QPaintEvent *event)
{
    //通过这种方式可以将图片平铺到窗口上
    //使用样式表可以很方便设置界面，而且非常高效，还能让界面和逻辑分离
    //不过在本例中由于是顶层窗口，所以直接设置样式表也不会显示。
    //所以样式表比较适合子窗口来使用。
    QPainter painter(this);
    painter.drawPixmap(rect(),QPixmap(":/images/share/selectmodel_page_bg2.png"),QRect());
}

void UserManager::on_usermanager_pushButton_selectfile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(
            this,
            tr("open a file."),
            "/data/usershare/jsdata/",
            tr("txtfile(*.txt);;All files(*.*)"));
    if (fileName.isEmpty()) {
        myHelper::ShowMessageBoxInfo("未正确选择文件！");

    }else
    {
        ui->usermanager_lineEdit_filepath->setText(fileName);
        QFile f(fileName);
        if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            myHelper::ShowMessageBoxInfo("打开文件失败");
        }else
        {
            // 获取文件的数据
            // QTextCodec *codec=QTextCodec::codecForName("utf-8");
            QByteArray con=f.readAll();
            // 按指定编码格式修改获取的数据
            QString str=QString(con).toUtf8();
            // QString str=codec->toUnicode(con);

            // 输出数据，格式正常
            QStringList rowInfoList=str.split("\n");

            for(QString rowInfo:rowInfoList){
                QStringList userInfo=rowInfo.split("\t");
                USERINFO_TABLE_DATA userdata;
                for(int i=0;i<userInfo.length();i++)
                {
                    switch (i) {
                    case 0:
                        userdata.UserID=userInfo.at(0);
                        break;
                    case 1:
                        userdata.UserName=userInfo.at(1);
                        break;
                    case 2:
                        userdata.UserPWD=userInfo.at(2);
                        break;
                    case 3:
                        userdata.UserSex=userInfo.at(3);
                        break;
                    case 4:
                        userdata.UserAge=userInfo.at(4);
                        break;
                    }

                }
                m_userInfoTableHash.insert(userdata.UserID,userdata);

            }
            f.close();
            RefreshTable();
        }

    }

}

void UserManager::initTableView()
{
    //自定义表头操作
    m_pTableHeader = new TableViewHeader(Qt::Horizontal, this);//表头
    m_pTableHeader->setStretchLastSection(true);//表头最后一列填充
    ui->tableView->setHorizontalHeader(m_pTableHeader);//设置表头
    ui->tableView->verticalHeader()->setFont(QFont( "黑体", 22, QFont::Black ));


    //创建model（目前使用的是标准数据模型，可以自定义数据模型），绑定model
    m_pTableModel = new QStandardItemModel(this);
    ui->tableView->setModel(m_pTableModel);//设置model
    ui->tableView->verticalHeader()->hide();


    //创建表头信息
    QStringList headerList;
    headerList << " " << tr("序号")   << tr("用户名")<< tr("姓名") << tr("密码") << tr("性别") << tr("年龄");
    m_pTableModel->setHorizontalHeaderLabels(headerList);


    //单击
    connect(ui->tableView, &QTableView::clicked,this, &UserManager::on_tableViewClick);
    //双击
    connect(ui->tableView, &QTableView::doubleClicked,this, &UserManager::on_tableViewDbClick);

    //标题头排序
    connect(ui->tableView->horizontalHeader(), &QHeaderView::sectionClicked,this, &UserManager::on_tableViewSort);
    //全选
    connect(m_pTableHeader, &TableViewHeader::stateChanged,this, &UserManager::on_tableViewSelectAllCheckBoxClick);

    //设置列宽
    setColumnWidth();

}
/*************************
 * QTableView-单击事件
 * ***********************/
void UserManager::on_tableViewClick(QModelIndex nIndex)
{


    int nRow = nIndex.row();
    int nCol = nIndex.column();

    Qt::CheckState oldState = m_pTableModel->item(nRow, COLUMN_CHECKBOX)->checkState();
    Qt::CheckState newState;

    if(oldState == Qt::Unchecked)
    {
        newState = Qt::Checked;
        m_nCheckedCount++;
    }
    else
    {
        newState = Qt::Unchecked;
        m_nCheckedCount--;
    }
    m_pTableModel->item(nRow, COLUMN_CHECKBOX)->setCheckState(newState);

    if(newState == Qt::Unchecked || m_nCheckedCount == m_pTableModel->rowCount())
    {
        m_pTableHeader->onStateChanged(newState);//改变标题栏的全选状态
    }
}

/*************************
 * QTableView-双击事件
 * ***********************/
void UserManager::on_tableViewDbClick(QModelIndex nIndex)
{


    int row = nIndex.row();

    qDebug() << "Db Click row:" << row;
}
/*************************
 * QTableView-排序
 * ***********************/
void UserManager::on_tableViewSort(int nColumn)
{

    //点击表头实现排序
    ui->tableView->horizontalHeader()->setSortIndicatorShown(true);
    ui->tableView->sortByColumn(nColumn,Qt::SortOrder::AscendingOrder);
}
/*************************
 * QTableView-响应表头全选操作
 * ***********************/
void UserManager::on_tableViewSelectAllCheckBoxClick(Qt::CheckState state)
{
    int nRowCount = m_pTableModel->rowCount();//当前行数

    for(int i = 0; i < nRowCount; i++)
    {
        m_pTableModel->item(i, COLUMN_CHECKBOX)->setCheckState(state);
    }
}

/*************************
 * QTableView-设置列宽
 * ***********************/
void UserManager::setColumnWidth()
{
    ui->tableView->setColumnWidth(COLUMN_CHECKBOX,100);
    ui->tableView->setColumnWidth(COLUMN_PWD,400);
    ui->tableView->setColumnWidth(COLUMN_NO, 200);
    ui->tableView->setColumnWidth(COLUMN_ID, 450);

    ui->tableView->setColumnWidth(COLUMN_NAME, 400);
    ui->tableView->setColumnWidth(COLUMN_SEX, 200);
    ui->tableView->setColumnWidth(COLUMN_AGE, 200);

}
void UserManager::resizeEvent(QResizeEvent *)
{
    setColumnWidth();
}
void UserManager::RefreshTable()
{
    if(m_pTableModel->rowCount() > 0)
    {
        m_pTableModel->removeRows(0, m_pTableModel->rowCount());
    }

    QHashUserInfoTableIterator i = m_userInfoTableHash.begin();
    int row = 0;
    for(; i != m_userInfoTableHash.end(); ++i)
    {
        USERINFO_TABLE_DATA data = i.value();

        //可以通过insertRow和setData增加数据
        m_pTableModel->insertRow(row, QModelIndex());
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_CHECKBOX), "");
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_NO), row+1);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_ID), data.UserID);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_NAME), data.UserName);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_PWD), data.UserPWD);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_SEX), data.UserSex);
        m_pTableModel->setData(m_pTableModel->index(row, COLUMN_AGE), data.UserAge);


        //也可以通过setItem增加数据
        //m_pTableModel->setItem(row, COLUMN_CHECKBOX, new QStandardItem(""));

        // 设置全部列居中显示
        for(int j = COLUMN_NO; j <= COLUMN_AGE; j++)
        {
            m_pTableModel->item(row, j)->setTextAlignment(Qt::AlignCenter);
        }
        row++;
    }
}

void UserManager::on_pushButton_exit_clicked()
{
    close();
}

void UserManager::on_usermanager_pushButton_input_clicked()
{
    int nRowCount = m_pTableModel->rowCount();//当前行数
    if(nRowCount<=0)
    {
        myHelper::ShowMessageBoxInfo("当前未有数据导入！");
    }else
    {
        QString file=Constant::DataBasePath;
        Qt::HANDLE threadId = QThread::currentThreadId();
        QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

        MySql *mySql = new MySql(file,threadIdStr);
        m_userInfoTableHash.clear();//清除数据
        for(int i = 0; i < nRowCount; i++)
        {
            UserInfoBean uib;
            qDebug()<<m_pTableModel->item(i,COLUMN_ID)->text();
            uib.UserID=m_pTableModel->item(i,COLUMN_ID)->text();
            uib.UserName=m_pTableModel->item(i,COLUMN_NAME)->text();
            uib.UserPwd=m_pTableModel->item(i,COLUMN_PWD)->text();
            uib.UserAge=m_pTableModel->item(i,COLUMN_AGE)->text();
            uib.UserSex=m_pTableModel->item(i,COLUMN_SEX)->text();
            uib.IsLogin="0";
            USERINFO_TABLE_DATA userdata;
            userdata.UserID=uib.UserID;
            userdata.UserName=uib.UserName;
            userdata.UserAge=uib.UserAge;
            userdata.UserSex=uib.UserSex;
            userdata.UserPWD=uib.UserPwd;

            if(mySql->Query(m_pTableModel->item(i,COLUMN_ID)->text()))
            {
                //将数据库中存在的用户显示出来
                qDebug()<<"exist";
                m_userInfoTableHash.insert(userdata.UserID,userdata);
            }else
            {
                if(mySql->MyInsert(uib))
                {
                    qDebug()<<"insert success";
                }else
                {
                    qDebug()<<"insert fail";
                }
            }
        }
        RefreshTable();
        delete  mySql;
        int rowNum=m_pTableModel->rowCount();//当前行数;

        if(rowNum>0)
        {
            myHelper::ShowMessageBoxInfo("数据库中存在以下用户信息！");
        }else
        {
             myHelper::ShowMessageBoxInfo("导入成功！");
        }
    }
}


void UserManager::on_usermanager_pushButton_delete_clicked()
{

    int nRowCount = m_pTableModel->rowCount();//当前行数
    int selRow=0;
    for(int i=0;i<nRowCount;i++)
    {
        if(m_pTableModel->item(i,COLUMN_CHECKBOX)->checkState()==Qt::Checked)
        {
            selRow++;
        }
    }
    if(selRow<=0)
    {
        myHelper::ShowMessageBoxInfo("您未选中要删除的行！");
    }else
    {
        if(myHelper::ShowMessageBoxQuesion("您确定要删除选中用户信息吗？"))
        {
            QString file=Constant::DataBasePath;
            Qt::HANDLE threadId = QThread::currentThreadId();
            QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

            MySql *mySql = new MySql(file,threadIdStr);
            for(int i=0;i<nRowCount;i++)
            {
                if(m_pTableModel->item(i,COLUMN_CHECKBOX)->checkState()==Qt::Checked)
                {
                    mySql->MyDelete(m_pTableModel->item(i,COLUMN_ID)->text());
                    m_userInfoTableHash.remove(m_pTableModel->item(i,COLUMN_ID)->text());
                }
            }
            delete mySql;
            RefreshTable();
        }
    }

}

void UserManager::on_usermanager_pushButton_query_clicked()
{
    QString file=Constant::DataBasePath;
    Qt::HANDLE threadId = QThread::currentThreadId();
    QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

    MySql *mySql = new MySql(file,threadIdStr);
    QList<UserInfoBean>uibs=mySql->QueryAll();
    m_userInfoTableHash.clear();//清除数据
    if(uibs.size()>0)
        ui->usermanager_pushButton_delete->setEnabled(true);
    for(int i=0;i<uibs.size();i++)
    {
        UserInfoBean uib=uibs.at(i);
        USERINFO_TABLE_DATA userdata;
        userdata.UserID=uib.UserID;
        userdata.UserName=uib.UserName;
        userdata.UserAge=uib.UserAge;
        userdata.UserSex=uib.UserSex;
        userdata.UserPWD=uib.UserPwd;

        m_userInfoTableHash.insert(userdata.UserID,userdata);
    }
    RefreshTable();
    delete  mySql;
}

void UserManager::on_usermanager_pushbutton_update_clicked()
{
    int nRowCount = m_pTableModel->rowCount();//当前行数
    int selRow=0;
    for(int i=0;i<nRowCount;i++)
    {
        if(m_pTableModel->item(i,COLUMN_CHECKBOX)->checkState()==Qt::Checked)
        {
            selRow++;
        }
    }
    if(selRow==1)
    {
        UpdateInfo *updateinfo=new UpdateInfo;
        connect(this, SIGNAL(sendUserID(QString)),updateinfo, SLOT(getUserID(QString)));
        connect(updateinfo,SIGNAL(sendUpdateSucess(bool)),this,SLOT(getUpdateInfo(bool)));
        QString UserID;
        for(int i=0;i<nRowCount;i++)
        {
            if(m_pTableModel->item(i,COLUMN_CHECKBOX)->checkState()==Qt::Checked){
                UserID=m_pTableModel->item(i,COLUMN_ID)->text();
                break;
            }
        }
        emit sendUserID(UserID);
        updateinfo->show();


    }else
    {
        myHelper::ShowMessageBoxInfo("请您选中一行用户信息！");
    }
}
void UserManager::getUpdateInfo(bool b)
{
    if(b)
    {
        QString file=Constant::DataBasePath;
        Qt::HANDLE threadId = QThread::currentThreadId();
        QString threadIdStr = QString::number(reinterpret_cast<quintptr>(threadId));

        MySql *mySql = new MySql(file,threadIdStr);
        QList<UserInfoBean>uibs=mySql->QueryAll();
        m_userInfoTableHash.clear();//清除数据
        if(uibs.size()>0)
            ui->usermanager_pushButton_delete->setEnabled(true);
        for(int i=0;i<uibs.size();i++)
        {
            UserInfoBean uib=uibs.at(i);
            USERINFO_TABLE_DATA userdata;
            userdata.UserID=uib.UserID;
            userdata.UserName=uib.UserName;
            userdata.UserAge=uib.UserAge;
            userdata.UserSex=uib.UserSex;
            userdata.UserPWD=uib.UserPwd;
            m_userInfoTableHash.insert(userdata.UserID,userdata);
        }
        RefreshTable();
        delete  mySql;
    }
}
